package controllerIndex

import (
	"github.com/gin-gonic/gin"
	"go-member/controller/common"
	"go-member/db"
	"go-member/model"
	"go-member/tool"
	"strconv"
)

func NumberList() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		mysql := db.InitMysql()
		defer mysql.Close()
		page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
		name := ctx.Query("name")
		phone := ctx.Query("phone")
		if name != "" {
			mysql = mysql.Where("name LIKE ?", "%"+name+"%")
		}
		if phone != "" {
			if len(phone) == 4 {
				mysql = mysql.Where("RIGHT(phone,4) = ?", phone)
			} else {
				mysql = mysql.Where("phone = ?", phone)
			}
		}

		var count uint
		numberLog := new([]model.NumberLog)
		mysql.Model(&numberLog).Debug().Count(&count)
		pageSize, _ := strconv.Atoi(tool.GetEnvDefault("web-number-page-size", "10"))
		mysql.Limit(pageSize).Offset((page - 1) * pageSize).Order("id DESC").Debug().Find(numberLog)
		dataStruct := model.NumberLogStruct{}
		dataStruct.List = numberLog
		dataStruct.Total = count
		dataStruct.CurrentPage = uint(page)
		common.Success(ctx, "success", dataStruct)
	}
}
